package main

import (
	"fmt"
	"log"
	"net/http"
	//"runtime"
	consulapi "github.com/hashicorp/consul/api"
)

type RegServerInfo struct {
	SrvID string
	Name  string
	Addr  string
	Port  int

	ChkPort   string
	Tags      []string
	TimeOut   string
	Interval  string
	DeRegtime string
}

func NewRegServerInfo(svrID string, name string, addr string,
	port int, chkPort string, tags string) *RegServerInfo {

	regServer := new(RegServerInfo)
	regServer.Init(svrID, name, addr,
		port, chkPort, tags,
		"2s", "5s",
		"30s")

	return regServer

}

func (self *RegServerInfo) Init(srvID string, name string, addr string,
	port int, chkPort string, tags string,
	timeout string, interval string, deregtime string) {
	self.SrvID = srvID
	self.Name = name
	self.Addr = addr
	self.Port = port

	self.ChkPort = chkPort
	self.Tags = []string{tags}
	self.TimeOut = timeout
	self.Interval = interval
	self.DeRegtime = deregtime
}

func (self *RegServerInfo) ConsulCheck(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "consulCheck")
	//num := runtime.NumGoroutine()
	//fmt.Printf("current goroutines is: %d \n", num)
}

func (self *RegServerInfo) RegisterServer(addr string) {

	config := consulapi.DefaultConfig()
	config.Address = addr
	//fmt.Println("addr:", config.Address)
	client, err := consulapi.NewClient(config)

	if err != nil {
		log.Fatal("consul client error : ", err)
	}

	checkPort := self.ChkPort

	registration := new(consulapi.AgentServiceRegistration)
	registration.ID = self.SrvID
	registration.Name = self.Name
	registration.Port = self.Port
	registration.Tags = self.Tags
	registration.Address = self.Addr
	registration.Check = &consulapi.AgentServiceCheck{
		HTTP:                           fmt.Sprintf("http://%s:%s%s", registration.Address, checkPort, "/check"),
		Timeout:                        self.TimeOut,
		Interval:                       self.Interval,
		DeregisterCriticalServiceAfter: self.DeRegtime, //check失败后time秒删除本服务
	}

	err = client.Agent().ServiceRegister(registration)

	if err != nil {
		log.Fatal("register server error : ", err)
	}

	http.HandleFunc("/check", self.ConsulCheck)
	http.ListenAndServe(fmt.Sprintf(":%s", checkPort), nil)

}

func (self *RegServerInfo) Run(addr string) {
	go self.RegisterServer(addr)
}
